<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>scrachcard</title>
</head>
<body>
<canvas id="scrachcard"></canvas>
<script>
(function(){
    var canvas = document.querySelector('#scrachcard'),
            ctx = canvas.getContext('2d'),
            w = 0,
            h = 0,
            result = 0,
            data = null,
            touched = false,
            painted = 0;
    result = scrachResult();
    var theEvent = {
        touchUp:function(e){
            e.preventDefault();
            touched = false;
            showResult();
        },
        touchDown: function (e) {
            e.preventDefault();
            touched = true;
        },
        touchMove: function (e) {
            e.preventDefault();
            console.log(touched);
            if(touched){
                var x = e.pageX - canvas.offsetLeft,
                    y = e.pageY - canvas.offsetTop;
                ctx.beginPath();
                ctx.arc(x,y,10,0,Math.PI*2);
                ctx.fill();
            }
        }
    }


    init();
    cover();
    ctx.globalCompositeOperation = 'destination-out';
    canvas.addEventListener('mousedown',theEvent.touchDown);
    canvas.addEventListener('mouseup',theEvent.touchUp);
    canvas.addEventListener('mousemove',theEvent.touchMove);
    canvas.addEventListener('touchstart',theEvent.touchDown);
    canvas.addEventListener('touchend',theEvent.touchUp);
    canvas.addEventListener('touchmove',theEvent.touchMove);


    function init(){

        canvas.width = '200';
        canvas.height = '100';
        canvas.style.border='1px solid black';
        canvas.style.background = 'url(p_'+result+'.jpg)left top no-repeat';
        canvas.style.backgroundSize='cover';
        w = canvas.width,
        h = canvas.height;
    }
    function scrachResult(){
        var chance = Math.random()*10>5?0:1;
        return chance;
    }
    function cover(){
        ctx.fillStyle='gray';
        ctx.fillRect(0,0,w,h);
    }
    function showResult(){

        data = ctx.getImageData(0,0,w,h).data;

        for(var i=0;i<data.length;i++){
            if(data[i]==0){
                painted++;
            }
            if(painted>= data.length*0.3){
                return alert(result==0?'没中奖':'中奖了!');
            }
        }
        console.log(painted+'---------'+data.length);
    }
})()


</script>
</body>
</html>